package com.demo.gulimall.order.controller;

import com.demo.gulimall.common.utils.R;
import com.demo.gulimall.order.entity.Order;
import com.demo.gulimall.order.entity.OrderReturnReason;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

/**
 * @author Chen Yuan
 * @create 2023-06-26  11:00
 */
@RestController
@RequestMapping("/rabbit")
@Slf4j
public class RabbitController {
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@GetMapping("/sendmsg")
	public void rabbitSendMsg(@RequestParam("n") int n){
		for (int i = 0; i < n; i++) {
			String id = UUID.randomUUID().toString();
			if (i % 2 == 0) {
				OrderReturnReason returnReason = new OrderReturnReason();
				returnReason.setId(Long.parseLong(String.valueOf(i)))
						.setName("test")
						.setStatus(Byte.valueOf("1"))
						.setCreateTime(new Date());

				//转换并发送消息, 参数: 指定交换机、路由键、消息体、消息的唯一ID
				rabbitTemplate.convertAndSend("hello-java-exchange", "hello-java", returnReason, new CorrelationData(id));
				log.info("--> Rabbit 发送消息 - i:{} - OrderReturnReason", i);
			}else {
				Order order = new Order();
				order.setId(Long.parseLong(String.valueOf(i)));
				order.setOrderSn(id);
				order.setCreateTime(new Date());
				rabbitTemplate.convertAndSend("hello-java-exchange", "hello-java", order, new CorrelationData(id));
				log.info("--> Rabbit 发送消息 - i:{} - Order", i);
			}
		}
	}

	@GetMapping("/test/delayqueue")
	public R testOrderDelayQueue(){
		// 订单创建完成
		Order order = new Order();
		order.setOrderSn(UUID.randomUUID().toString());
		order.setCreateTime(new Date());

		// 向延时队列发送消息
		rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order);

		return R.ok(order.getOrderSn());
	}
}
